package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Query;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.RequestServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.exception.ParameterException;
import com.plusmoney.exception.RpcServerLogicalException;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
 * 获得某人的申请列表
 *
 * @author Administrator
 */
@WebServlet("/getHisRequestList")
public class GetHisRequestList extends AbstractServlet {
	private static final long serialVersionUID = -6524473373623928868L;

	private static final Logger logger = LoggerFactory.getLogger(GetHisRequestList.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * 数据格式:{applicant(被查看人的contact):xx,page:,dataNum:,"currentMonth":yyyy-MM,
	 * "siftingBy":"模板类型","currentStatus":"筛选的当前的审批状态 1，已批准，3已驳回，0审批中"}
	 * 0表示进行中，1表示已同意，2表示已全部归档，3表示已拒绝
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);

			Request request = getRequest(req);
			check(request);

			checkAuth(request, user);

			RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);
			Query query = getQuery(req, user, request);
			List<Request> list = requestServicePrx.getUserSubordinateRequestList(query);

			// 替换新版本的显示值
			ApprovalUtils.replaceNewExpenseValue(list);

			returnResponse(resp, list);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}

	private void returnResponse(HttpServletResponse resp, List<Request> requests) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", requests);

		logger.info(jsonObject.toJSONString());

		printJson(resp, jsonObject.toJSONString());
	}

	private void checkAuth(Request request, User user) throws Throwable {
		UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
		User applicant = userService.getUserByContactId(request.getApplicant());

		// 自己查看自己
		if (Objects.equals(user.getCompanyInfoId(), applicant.getCompanyInfoId())) {
			return;
		}

		if (userService.isLeader(user.getContactId(),request.getApplicant())){
			return;
		}

		throw new RpcServerLogicalException(1, "无权操作");
	}

	private Request getRequest(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);

		Request request;
		try {
			request = JSONObject.parseObject(reqBody, Request.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
		}
		return request;
	}

	protected void check(Request request) {
		if (request.getApplicant() == 0) {
			throw new ParameterException("请求ID不正确");
		}
	}


}
